package com.dtai.simulator

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.widget.AppCompatButton
import com.qiniu.qmedia.component.player.QAuthenticationErrorType
import com.qiniu.qmedia.component.player.QIPlayerAuthenticationListener
import com.qiniu.qmedia.component.player.QMediaModelBuilder
import com.qiniu.qmedia.component.player.QPlayerSetting
import com.qiniu.qmedia.component.player.QURLType
import com.qiniu.qmedia.ui.QTexturePlayerView
import org.json.JSONObject
import java.util.UUID

class MainActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        const val TAG: String = "MainActivity"
    }
    private lateinit var mWakeLock: PowerManager.WakeLock

    private lateinit var reverseCb: CheckBox

    private lateinit var mQTexturePlayerView: QTexturePlayerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        acquireWakeLock()

//        val rootView = findViewById<ConstraintLayout>(R.id.root_view)
//        for (btn in rootView.children) {
//            btn.setOnClickListener(this)
//        }
        bindClickListener()

        reverseCb = findViewById(R.id.reverse_cb)
        mQTexturePlayerView = findViewById(R.id.player_view)

        val mqttHelper = MqttHelper.getInstance()
        mqttHelper.initClient(UUID.randomUUID().toString())
        mqttHelper.connect(object : MqttHelper.ConnectionCallback {
            override fun onSuccess() {
                Log.d(TAG, "mqtt connect success")
            }

            override fun onError(throwable: Throwable?) {
                Log.d(TAG, "mqtt connect failed")
            }
        })
//        mqttHelper.subscribe(MqttHelper.TOPIC_SUB) { payload ->
//            val msg = mHandler.obtainMessage(100)
//            msg.obj = payload
//            mHandler.sendMessage(msg)
//        }

        initPlayer()
    }

    private fun bindClickListener() {
        findViewById<AppCompatButton>(R.id.forward_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.backward_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.towards_left_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.towards_right_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.turn_left_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.turn_right_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.handshake_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.wave_hand_btn).setOnClickListener(this)
        findViewById<AppCompatButton>(R.id.playback_btn).setOnClickListener(this)
    }

    override fun onClick(v: View) {
        val reverse = reverseCb.isChecked
        when(v.id) {
            R.id.forward_btn -> { // 前进
                publish(if (reverse) "s" else "w")
            }
            R.id.backward_btn -> { // 后退
                publish(if (reverse) "w" else "s")
            }
            R.id.towards_left_btn -> { // 向左
                publish(if (reverse) "d" else "a")
            }
            R.id.towards_right_btn -> { // 向右
                publish(if (reverse) "a" else "d")
            }
            R.id.turn_left_btn -> { // 左转
                publish(if (reverse) "e" else "q")
            }
            R.id.turn_right_btn -> { // 右转
                publish(if (reverse) "q" else "e")
            }
            R.id.handshake_btn -> { // 握手
                publish("v")
            }
            R.id.wave_hand_btn -> { // 挥手
                publish("x")
            }
            R.id.playback_btn -> { // 回放
                publish("playback")
            }
        }
    }

    private fun publish(cmd: String) {
        val jsonObject = JSONObject().apply {
            put("cmd", cmd)
        }
        Log.d(TAG, "cmd is $cmd")
        MqttHelper.getInstance().publish("controller/cmd", cmd)
    }

    private fun initPlayer() {
        mQTexturePlayerView.playerControlHandler.init(this)
        mQTexturePlayerView.playerControlHandler.setDecodeType(QPlayerSetting.QPlayerDecoder.QPLAYER_DECODER_SETTING_AUTO)
        mQTexturePlayerView.playerControlHandler.setSeekMode(QPlayerSetting.QPlayerSeek.QPLAYER_SEEK_SETTING_NORMAL)
        mQTexturePlayerView.playerControlHandler.setStartAction(QPlayerSetting.QPlayerStart.QPLAYER_START_SETTING_PLAYING)
        mQTexturePlayerView.playerControlHandler.setSpeed(1.0f)
        mQTexturePlayerView.playerRenderHandler.setRenderRatio(QPlayerSetting.QPlayerRenderRatio.QPLAYER_RATIO_SETTING_AUTO)
        val listener =  object: QIPlayerAuthenticationListener {
            /**
             * 鉴权失败回调，同时，会停止当前的视频播放，且状态切换成 @see[QPlayerState.ERROR]
             */
            override fun on_authentication_failed(error_type: QAuthenticationErrorType) {
                Log.d(TAG, "on_authentication_failed error_type=$error_type")
            }
            /**
             * 鉴权成功回调
             */
            override fun on_authentication_success() {
                Log.d(TAG, "on_authentication_success")
            }
        }
        //添加监听
        mQTexturePlayerView.playerControlHandler.addPlayerAuthenticationListener(listener)


        val builder = QMediaModelBuilder()
        builder.addStreamElement("", QURLType.QAUDIO_AND_VIDEO, 0, Config.ADDRESS, true)
        val model = builder.build(true)
        mQTexturePlayerView.playerControlHandler.playMediaModel(model, 0)
    }

    override fun onDestroy() {
        mQTexturePlayerView.playerControlHandler.release()
        releaseWakeLock()
        super.onDestroy()
    }

    @SuppressLint("InvalidWakeLockTag")
    private fun acquireWakeLock() {
        val powerManager =getSystemService(Context.POWER_SERVICE) as PowerManager
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "keep_player_activate")
        mWakeLock.setReferenceCounted(false)
    }

    private fun releaseWakeLock() {
        mWakeLock.release()
    }
}













